package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ModifyLogEnum;
import com.py.credit.service.ModifyLogService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

@RestController
@RequestMapping("/modifyLog")
public class ModifyLogController {

    private final static String FRONT_TABLE_ID = "process";
    @Autowired
    private ModifyLogService modifyLogService;
    @Autowired
    private XypjRemoteBaseService xypjRemoteBaseService;

    @IgnoreAuthority
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/getModifyOperById.json")
    public RestServiceResult<List<LinkedHashMap>> getModifyOperById(
            @RequestParam(value = "processId", defaultValue = "") String processId,
            @RequestParam(value = "tableId", defaultValue = "") String tableId,
            @RequestParam(value = "id", defaultValue = "") String id,
            @RequestParam(value = "zxcz", defaultValue = "") String zxcz) {
        RestServiceResult<List<LinkedHashMap>> r = new RestServiceResult<>();
        RestServiceResult<LinkedHashMap> r1 = new RestServiceResult<>();
        try {
            List<LinkedHashMap> params = modifyLogService.selectModifyOperById(processId);

            if (!zxcz.equals("I") && null != id && !("").equals(id)) {
                r1 = xypjRemoteBaseService.getTableInfoById(tableId, id,"");
            }
            params.add(r1.getData());
            r.setData(params);
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("修改操作查询失败！");
        }
        return r;
    }

    @RequestMapping(value = "/selectModifyLogByForPage.json")
    public RestServiceResult<List<LinkedHashMap>> selectModifyLogByForPage(
            @RequestParam(value = "mainType", defaultValue = "") String mainType,
            @RequestParam(value = "tablename", defaultValue = "") String tablename,
            @RequestParam(value = "mainName", defaultValue = "") String mainName,
            @RequestParam(value = "bm", defaultValue = "") String bm, Page page) {
        @SuppressWarnings("rawtypes")
        RestServiceResult<List<LinkedHashMap>> r = new RestServiceResult<List<LinkedHashMap>>();
        try {
            r.setData(modifyLogService.selectModifyLogByForPage(mainType, tablename, mainName, bm, page));
            r.setCount(page.getTotalCount());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("修改日志查询失败！");
        }
        return r;
    }

    @IgnoreAuthority
    @RequestMapping(value = "/updateCheckById.do")
    public RestServiceResult<Object> updateCheckById(@RequestParam(value = "id", defaultValue = "") String id,
                                                     @RequestParam(value = "shzt", defaultValue = "") String shzt,
                                                     @RequestParam(value = "bz", defaultValue = "") String bz,
                                                     @RequestParam(value = "shyj", defaultValue = "") String shyj,
                                                     @RequestParam(value = "shr", defaultValue = "") String shr,
                                                     @RequestParam(value = "recordId", defaultValue = "") String recordId,
                                                     @RequestParam(value = "idAuditing", defaultValue = "") String idAuditing) {
        RestServiceResult<Object> r = new RestServiceResult<Object>();
        try {
            modifyLogService.updateCheckById(id, shzt, bz, shyj, shr);
            modifyLogService.updateCheckNoteById(recordId, idAuditing);
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("添加修改日志的日志失败！");
        }
        return r;
    }

    @IgnoreAuthority
    @RequestMapping(value = "/selectUserOperForPage.json")
    public RestServiceResult<List<LinkedHashMap>> selectUserOperForPage(
            @RequestParam(value = "mainType", defaultValue = "") String mainType,
            @RequestParam(value = "username", defaultValue = "") String username,
            @RequestParam(value = "ztmc", defaultValue = "") String ztmc, Page page) {
        RestServiceResult<List<LinkedHashMap>> r = new RestServiceResult<List<LinkedHashMap>>();
        try {
            r.setData(modifyLogService.selectUserOperForPage(mainType, username, ztmc, page));
            r.setCount(page.getTotalCount());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("用户操作查询失败！");
        }
        return r;

    }

    @RequestMapping(value = "/selectCheckResultByCjrForPage.json")
    public RestServiceResult<List<LinkedHashMap>> selectCheckResultByCjrForPage(
            @RequestParam(value = "cjr", defaultValue = "") String cjr, Page page) {
        RestServiceResult<List<LinkedHashMap>> r = new RestServiceResult<List<LinkedHashMap>>();
        try {
            r.setData(modifyLogService.selectCheckResultByCjrForPage(cjr, page));
            r.setCount(page.getTotalCount());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("用户操作核查结果查询失败！");
        }
        return r;

    }

    @RequestMapping(value = "/getOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
        RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
        try {
                r = new RestServiceResult<>(ModifyLogEnum.getOptionalColumns());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常");
        }
        return r;
    }

    @RequestMapping(value = "/getTableList.json")
    public RestServiceResult<List<LinkedHashMap<String, Object>>> getTableList(
            @RequestParam(value = "mainType", defaultValue = "") String mainType,
            @RequestParam(value = "tablename", defaultValue = "") String tablename,
            @RequestParam(value = "mainName", defaultValue = "") String mainName,
            @RequestParam(value = "bm", defaultValue = "") String bm,
            @RequestParam(value = "condition", defaultValue = "") String condition, Page page,
            HttpServletRequest request) {

        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<List<LinkedHashMap<String, Object>>> result = new RestServiceResult<List<LinkedHashMap<String, Object>>>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }

        String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? ModifyLogEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        // condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
        RestServiceResult<List<LinkedHashMap<String, Object>>> r = new RestServiceResult<List<LinkedHashMap<String, Object>>>();
        String[] additionalColumns = {"id", "tableId", "recordId", "dataId", "shyj", "bz", "shr"};
        try {
            List<LinkedHashMap<String, Object>> tableList = modifyLogService.selectByConditionForPage(mainType,
                    tablename, mainName, bm, showColumns, additionalColumns, condition, page);
            r = new RestServiceResult<List<LinkedHashMap<String, Object>>>(page.getTotalCount(), tableList);
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常！");
        }
        return r;
    }

    @RequestMapping(value = "/exportModifyLog.json")
    public RestServiceResult<List<LinkedHashMap<String, Object>>> exportModifyLog(
            @RequestParam(value = "mainType", defaultValue = "") String mainType,
            @RequestParam(value = "tablename", defaultValue = "") String tablename,
            @RequestParam(value = "mainName", defaultValue = "") String mainName,
            @RequestParam(value = "bm", defaultValue = "") String bm,
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletResponse response, HttpServletRequest request) {
        page.setLimit(1000);
        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        List<OptionalColumn> optionalColumns = ModifyLogEnum.getOptionalColumns();
        List<LinkedHashMap<String, Object>> data;
        RestServiceResult<List<LinkedHashMap<String, Object>>> result = new RestServiceResult<List<LinkedHashMap<String, Object>>>();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        try {
            data = modifyLogService.selectByConditionForPage(mainType, tablename, mainName, bm, showColumns, null,
                    condition, page);
            if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
                return result;
            }
            ExcelUtil.downloadLinkExcel(response, data, "修改日志列表", "修改日志列表", showColumns, optionalColumns);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("报告领取导出异常，请稍后再试！");
            ExceptionLogger.error("报告领取导出异常！", e.getMessage(), e);
            return result;
        }
    }

    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
        RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
        try {
            r = new RestServiceResult<List<OptionalColumn>>(ModifyLogEnum.getAdvancedConditionColumns());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("系统异常");
        }
        return r;

    }

    /**
     * 手动选择展示列
     *
     * @param columns
     * @return
     */
    @RequestMapping(value = "/addShowColunms.json")
    public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
                                                    HttpServletRequest request) {
        RestServiceResult<String> result = new RestServiceResult<String>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#addShowColunms", "未获取到当前用户信息！");
                return result;
            }
            String column = StringUtils.join(columns, ",");
            MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, StringUtils.split(column, ","));
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        return new RestServiceResult<String>();
    }
}
